package com.syh.gateway.filter;

import com.syh.bscommon.Util.UserHolder;
import com.syh.bscommon.interceptor.LoginCheckInterceptor;
import com.syh.bscommon.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        // Exclude certain paths from being filtered
        if (path.startsWith("/swagger-resources") ||
                path.equals("/v2/api-docs") ||
                path.startsWith("/v3/api-docs") ||
                path.startsWith("/webjars") ||
                path.startsWith("/swagger-ui") ||
                path.equals("/favicon.ico") ||
                path.equals("/user/login") ||
                path.equals("/user/register") ||
                path.equals("/user/reset-password")) {
            return chain.filter(exchange);
        }

        return loginCheckInterceptor.preHandle(exchange).flatMap(isAllowed -> {
            if (Boolean.FALSE.equals(isAllowed)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            // 获取用户信息
            UserInfo userInfo = UserHolder.getUser();

            // 将用户信息放入请求头部
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpRequest newRequest = request.mutate()
                    .header("X-User-Id", String.valueOf(userInfo.getId()))
                    .header("X-User-Email", userInfo.getEmail())
                    .header("X-Company-Id", String.valueOf(userInfo.getCompanyId()))
                    .build();
            log.info(userInfo.getEmail());

            // 创建新的交换对象，使用带有用户信息的新请求
            ServerWebExchange newExchange = exchange.mutate()
                    .request(newRequest)
                    .build();

            // 继续处理请求
            return chain.filter(newExchange)
                    .doFinally(signalType -> UserHolder.removeUser()); // 请求完成后释放资源
        });
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
